using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Application.DTOs;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 内容发布流程管理接口。
    /// 提供内容发布、撤销、历史记录、队列状态跟踪等相关 API。
    /// </summary>
    [ApiController]
    [Route("api/publishing")]
    public class PublishingController : ControllerBase
    {
        /// <summary>
        /// 发布应用服务接口
        /// </summary>
        private readonly IPublishingAppService _service;
        
        /// <summary>
        /// 构造函数，注入发布服务
        /// </summary>
        /// <param name="service">发布应用服务接口</param>
        public PublishingController(IPublishingAppService service)
        {
            _service = service;
        }

        /// <summary>
        /// 发布指定ID的内容
        /// </summary>
        /// <param name="contentId">内容项ID</param>
        /// <param name="dto">发布请求数据传输对象</param>
        /// <returns>发布结果响应</returns>
        [Authorize]
        [HttpPost("{contentId}")]
        public async Task<IActionResult> Publish(long contentId, [FromBody] PublishRequestDto dto)
        {
            await _service.PublishAsync(contentId, dto.PublishTime.ToString("o"), dto.TargetEnvironment);
            return Ok(new { success = true });
        }

        /// <summary>
        /// 撤销指定内容的发布状态
        /// </summary>
        /// <param name="contentId">内容项ID</param>
        /// <returns>撤销发布结果响应</returns>
        [Authorize]
        [HttpDelete("{contentId}")]
        public async Task<IActionResult> Unpublish(long contentId)
        {
            await _service.UnpublishAsync(contentId);
            return Ok(new { success = true });
        }

        /// <summary>
        /// 获取指定内容的发布历史记录
        /// </summary>
        /// <param name="contentId">内容项ID</param>
        /// <param name="page">页码，默认第1页</param>
        /// <param name="limit">每页数量限制，默认10条</param>
        /// <returns>发布历史记录列表</returns>
        [Authorize]
        [HttpGet("history/{contentId}")]
        public async Task<IActionResult> GetPublishHistory(long contentId, int page = 1, int limit = 10)
            => Ok(await _service.GetPublishHistory(contentId, page, limit));

        /// <summary>
        /// 获取当前发布队列状态
        /// </summary>
        /// <returns>发布队列状态列表</returns>
        [Authorize]
        [HttpGet("queue")]
        public async Task<IActionResult> GetPublishQueue(string? status = null, int page = 1, int limit = 10)
            => Ok(await _service.GetPublishQueueAsync(status, page, limit));
    }
}
